/*
* 微信素材管理Api
*/
var WechatApi       = require('./WechatApi');
var uploadConfig    = require('../../uploadconfig.json');
var config          = require('../../configuration.json');
var qs              = require('qs');
var rpc             = require('../rpc/rpcUtility');
var utility         = require('../utilities/utilities');
var fs              = require('fs');
var uploadconfig    = require('../../uploadconfig.json')
class MaterialApi extends WechatApi{
    constructor(appid){
        super(appid);
    }
    *uploadTempImageMaterial(material){
          var that = this;
        console.log('save file')
            let fileResult = yield utility.downloadFile4upload('local',material,uploadconfig.material,null)
            console.log('get file',fileResult);
            var form = {media:fs.createReadStream(fileResult.filePath)};

            let tokenResult = yield that.updateAccessToken();
              let url = `https://api.weixin.qq.com/cgi-bin/media/upload?access_token=${tokenResult.access_token}&type=image`;
              let option = {
                method:'POST',
                url:url,
                json:true,
                formData:form
              }
              var requestResult  = yield rpc.request(option);
              console.log('requestResult',requestResult);
              if (requestResult.successed==true){
                  return {successed:true,media_id:requestResult.body.media_id};
              }
              return {successed:false};
    }
    /**
     * 上传素材到公众号
     * @param {*} type 
     * @param {*} material 
     */
    *uploadMaterial(type,material){
          var that = this;
          var form = {}
          var uploadUrl = '';
          if(type === 'pic') uploadUrl ='https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=';
          if(type === 'other') uploadUrl = 'https://api.weixin.qq.com/cgi-bin/material/add_material?type=image&access_token=';
          if(type === 'news'){
            uploadUrl = 'https://api.weixin.qq.com/cgi-bin/material/add_news?access_token=';
            form = material
          }else{
            let fileResult = yield utility.downloadFile4upload('local',material,uploadconfig.material,null)
            
            form.media = fs.createReadStream(fileResult.filePath);
          }
        //   return new Promise(function(resolve,reject){
            let tokenResult = yield that.updateAccessToken();
            
            //that.fetchAccessToken().then(function(data){
              let url = uploadUrl + tokenResult.access_token;
              let option = {
                
                method:'POST',
                url:url,
                json:true,
                formData:    form
              }
              //(type == 'news') ? (option.body = form) : (option.formData = form); //上传数据的方式不同
              var requestResult  = yield rpc.request(option);
              return requestResult;
            //   if (requestResult.successed == true) 
            //     return (requestResult)
            //   else
            //     return (requestResult);
        //     });
    }
    /**
     * 获取素材
     * @param {*} mediaId 
     * @param {*} permanent 
     */
    // getMaterial(mediaId,permanent){
    //     var that = this;
    //     var getUrl = permanent ? api.getPermMaterial : api.getTempMaterial;
    //     return new Promise(function(resolve,reject){
    //       that.fetchAccessToken().then(function(data){
    //         var url = getUrl + 'access_token=' + data.access_token;
    //         if(!permanent) url += '&media_id=' + mediaId;
    //         resolve(url)
    //       });
    //     });
    //   }
    /**
     * 删除素材
     */
    // delelteMaterial(mediaId){
    //     var that = this;
    //     return new Promise(function(resolve,reject){
    //       that.fetchAccessToken().then(function(data){
    //         var url = api.delPermMaterial + 'access_token=' + data.access_token;
    //         var form = {media_id:mediaId}
    //         request({url:url,method:'POST',formData:form,json:true}).then(function(response){
    //           var _data = response.body;
    //           if(_data.errcode === '0'){
    //             resolve();
    //           }else{
    //             throw new Error('delete permanent material failed!');
    //           }
    //         }).catch(function(err){
    //           reject(err);
    //         });
    //       });
    //     });
    //   }
}

exports = module.exports = MaterialApi;